<template>
  <div class="slider-nav h-full pos-relative">
    <div
      class="nav-box pos-absolute w-full h-full border-rounded"
      ref="sliderNavRef"
      @mouseenter="handleSilderEnter"
      @mouseleave="handleSilderLeave"
    >
      <div class="bg-gray-50">
        <div
          v-for="item in menusList"
          :key="item.id"
          class="px-2 py-2 hover:bg-gray-100"
          @mouseenter="handleMenuEnter(item)"
        >
          <router-link to="/" class="flex items-center">
            <span class="pr-1">
              <el-icon :size="18"><Lock /> </el-icon>
            </span>
            <span class="text-gray-600 text-3.5"> {{ item.name }}</span>
          </router-link>
        </div>
      </div>
    </div>
    <!-- 添加连接桥，消除菜单间隙[2](@ref) -->
    <!-- 间隙桥 - 帮助鼠标在菜单间移动 -->
    <div class="gap-bridge" @mouseenter="keepSubmenuVisible()"></div>
    <Transition name="fade">
      <div
        v-show="isShow"
        class="absolute top-0 w-full h-full bg-white border-1 border-solid border-red border-rounded-2xl p-3"
        style="width: 860px; height: 560px; z-index: 9999; left: 100%"
        @mouseenter="handleSubmenuEnter"
        @mouseleave="handleSubmenuLeave"
      >
        <div class="flex items-center px-5 py-2">
          <router-link v-for="item in hotChannel" to="/">
            <span
              class="text-3.5 hover:text-red-500 hover:bg-gray-300 bg-gray-100 rounded-md mr-2 px-3 py-2 font-600"
            >
              {{ item }}
            </span>
          </router-link>
        </div>
        <div class="pt-3">
          <div v-for="item in childrenList" :key="item.id" class="mb-5">
            <div class="flex flex-start">
              <div class="w-20 pt-1">
                <div class="flex items-center justify-between" style="height: 21.5px">
                  <b class="text-3.5"> {{ item.name }}</b>
                  <el-icon :size="12" style="transform: translateY(-2px)"
                    ><ArrowRight
                  /></el-icon>
                </div>
              </div>
              <div class="flex items-center flex-wrap flex-1">
                <div v-for="child in item.children" :key="child.id" class="px-2 mb-2">
                  <router-link
                    to="/"
                    class="text-3.5 text-gray-600 hover:text-red-500 hover:underline"
                    >{{ child.name }}</router-link
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Transition>
  </div>
</template>
<script setup lang="ts">
import { ref, onUnmounted, watch,watchEffect, nextTick } from "vue";
import { menusList } from "@/mock/data/menu";
import { Lock, ArrowRight } from "@element-plus/icons-vue";
import { debounce } from "@/utils/util";

const sliderNavRef = ref<HTMLElement | null>(null);
const props = defineProps({
  show: {
    type: Number,
    default: null,
  },
});
const isShow = ref(false);
const isMainHovered = ref(false); // 主菜单悬停状态
const isSubmenuHovered = ref(false); // 子菜单悬停状态
const hoverTimer = ref<ReturnType<typeof setTimeout> | null>(null); // 隐藏定时器

const activeItem = ref<any>(null);
const childrenList = ref<any[]>([]);
const hotChannel = ref<any[]>([]);
// 主菜单鼠标进入
const handleSilderEnter = () => {
  isMainHovered.value = true;
  if (!sliderNavRef.value) return;
  sliderNavRef.value.classList.add("isOpen");
  showSubmenu(); // 显示子菜单（需实现具体逻辑，如获取activeItem）
};

// 主菜单鼠标离开
const handleSilderLeave = () => {
  isMainHovered.value = false;
  if (!sliderNavRef.value) return;
  sliderNavRef.value.classList.remove("isOpen");
  hideSubmenuWithDelay(); // 延迟隐藏子菜单
};

// 子菜单鼠标进入
const handleSubmenuEnter = () => {
  isSubmenuHovered.value = true;
  clearHideTimer(); // 清除隐藏定时器（防止子菜单被立即隐藏）
};

// 子菜单鼠标离开
const handleSubmenuLeave = () => {
  isSubmenuHovered.value = false;
  hideSubmenuWithDelay(); // 延迟隐藏子菜单
};

// 显示子菜单（需根据activeItem设置内容）
const showSubmenu = () => {
  if (activeItem.value) {
    childrenList.value = activeItem.value.children || [];
    hotChannel.value = activeItem.value.hotChannel || [];
    isShow.value = true;
  }
};

// 隐藏子菜单（带延迟）
const hideSubmenuWithDelay = async () => {
  await nextTick();
  clearHideTimer();
  console.log("开始延迟隐藏子菜单");
  const mainHovered = isMainHovered.value;
  const submenuHovered = isSubmenuHovered.value;
 hoverTimer.value= setTimeout(() => {
    console.log(!mainHovered && !submenuHovered);
    // 仅当主菜单和子菜单均未悬停时隐藏
    if (!mainHovered && !submenuHovered) {
      isShow.value = false;
    }
  }, 150); // 延迟150ms（与原代码保持一致）
};
const keepSubmenuVisible = () => {
  isShow.value = true;
};
// 点击子菜单项的处理
const handleSubmenuClick = () => {
  isShow.value = false;
  isSubmenuHovered.value = false;
};

// 清理定时器
const clearHideTimer = () => {
  if (hoverTimer.value) {
    clearTimeout(hoverTimer.value);
    hoverTimer.value = null;
  }
};
const handleMenuEnter = debounce((item: any) => {
  activeItem.value = item; // 添加延迟防止快速划过时误触
  hoverTimer.value = setTimeout(() => {
    childrenList.value = item.children || [];
    hotChannel.value = item.hotChannel || [];
  }, 200);
}, 150);

watch(
  () => props.show,
  (oldVal, newVal) => {
    console.log("oldVal", oldVal, "newVal", newVal);
    if (oldVal !== newVal) {
      console.log("隐藏子菜单：", isShow.value);
      isShow.value = false;
    }
  }
);
watchEffect(() => {
  console.log("isShow is now:", isShow.value);
  // watchEffect 会自动追踪依赖，但也要避免修改依赖
});
// 组件卸载时清理定时器
onUnmounted(() => {
  clearHideTimer();
});
</script>
<style lang="scss" scoped>
.slider-nav {
  height: 100%;
  transition: all 0.6s ease-in-out;

  .nav-box {
    top: 0;
    left: 0;
    z-index: 1;
    transition: all 0.3s ease-in-out;
    overflow: hidden;
    &.isOpen {
      height: 100%;
      overflow: visible;
    }
    .nav-item {
      height: 40px;
      line-height: 40px;
      &:hover {
        background-color: #f5f5f5;
      }
    }
  }
}
.gap-bridge {
  position: absolute;
  top: 0;
  right: -10px; /* 调整位置 */
  width: 10px;
  height: 100%;
  background: transparent;
  z-index: 9998;
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
  transform-origin: left center;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateX(10px);
}
</style>
